package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-graph-mgr/cache"
	"novel-graph-mgr/model"
	"novel-graph-mgr/pkg"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "NO",
		})
		return
	}
	var user model.User
	redis_key := "user_login" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次,禁止登陆",
		})
		return
	}
	err := model.DB.Where("username=?", username).Find(&user).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "NO",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "NO",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次,封禁两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "NO",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "Yes",
	})
	return
}

func NodelList(c *gin.Context) {
	var novel []model.Novel
	err := model.DB.Find(&novel).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "NO",
		})
		return
	}
	redis_key := "novel_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&novel)
		jsonData, _ := json.Marshal(novel)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &novel)
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "NO",
	})
	return
}
func NodelDetail(c *gin.Context) {
	id := c.Query("id")
	var novel model.Novel
	err := model.DB.Find(&novel).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "NO",
		})
		return
	}
	redis_key := "novel_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&novel)
		jsonData, _ := json.Marshal(novel)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &novel)
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "NO",
	})
	return
}
